package com.hmbe.service.impl;

import com.hmbe.dto.Result;
import com.hmbe.dto.UserDTO;
import com.hmbe.entity.SeckillVoucher;
import com.hmbe.entity.VoucherOrder;
import com.hmbe.mapper.VoucherOrderMapper;
import com.hmbe.service.ISeckillVoucherService;
import com.hmbe.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmbe.utils.IDGenUtil;
import com.hmbe.utils.SimpleRedisLock;
import com.hmbe.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private IDGenUtil idGenUtil;
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private StringRedisTemplate redisTemplate;


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //异步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    private final BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderThread());
    }

    // 用于线程池处理的任务
// 当初始化完毕后，就会去从对列中去拿信息
    private class VoucherOrderThread implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    // 1.获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    // 2.保存订单并扣减库存
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }

        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            //1.获取用户
            Long userId = voucherOrder.getUserId();
            // 2.创建锁对象
            SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId, redisTemplate);
            // 3.尝试获取锁
            boolean isLock = simpleRedisLock.tryLock(1200L);
            // 4.判断是否获得锁成功
            if (!isLock) {
                // 获取锁失败，直接返回失败或者重试
                log.error("不允许重复下单！");
            }
            try {
                //5.异步扣减数据库库存和保存订单信息
                decrementStock(voucherOrder.getVoucherId());
                save(voucherOrder);
            } catch (Exception e) {
                log.error("处理订单异常", e);
            } finally {
                // 释放锁
                simpleRedisLock.unlock();
            }
        }
    }

    @Override
    public Result seckillVoucherByLuaAndBMQ(Long voucherId) {
        //1.执行lua脚本
        UserDTO user = UserHolder.getUser();
        String orderId = idGenUtil.generateId("order");
        Long result = redisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                user.getId().toString(),
                orderId);

        //2.判断是否有购买资格
        int value = result.intValue();
        if (value != 0) {
            return Result.fail(result == 1 ? "库存不足" : "不能重复下单");
        }
        //3.将有购买资格的订单信息保存到消息队列
        createOrderAddToQueue(voucherId);
        //4.返回订单id
        return Result.ok(orderId);
    }

    private void createOrderAddToQueue(Long voucherId) {
        //5.创建订单
        //5.1使用全局id生成器生成订单id
        Long orderId = Long.valueOf(idGenUtil.generateId("order"));
        //5.2.保存订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        boolean success = orderTasks.add(voucherOrder);
        log.info("订单是否添加到队列:{}", success);
    }

    private void decrementStock(Long voucherId) {
        //1.数据库操作,扣减库存-1decrement1
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .update();
        if (!success) {
            //输出日志,库存不足
            log.error("库存不足");
        }
    }


    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.查询优惠券信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        //2.判断秒杀是否开始和结束
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始");
        }
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束");
        }
        //3.判断库存是否充足
        if (seckillVoucher.getStock() < 1) {
            System.out.println("库存不足");
            return Result.fail("库存不足");
        }
        //保证一人只能下一单
        UserDTO user = UserHolder.getUser();
        if (query().eq("user_id", user.getId()).eq("voucher_id", voucherId).count() > 0) {
            return Result.fail("一人只能下一单");
        }
        //4.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                //解决超卖问题
                .gt("stock", 0)
                .update();
        if (!success) {
            return Result.fail("库存不足");
        }
        //synchronized同步锁只能保证单机状态下一人一单,防止超卖,如果是在多个jvm中运行,需要使用分布式锁
        //尝试获取锁
        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + user.getId(), redisTemplate);
        Boolean isLock = simpleRedisLock.tryLock(1200);
        //获取锁失败
        if (!isLock) {
            return Result.fail("不要重复下单");
        }
        //获取锁成功,执行业务逻辑
        Long orderId = null;
        try {
            //5.创建订单
            orderId = createOrder(voucherId);
            //6.返回订单id
            return Result.ok(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            simpleRedisLock.unlock();
        }
        return Result.fail("下单失败");
    }

    @Transactional
    private Long createOrder(Long voucherId) {
        //5.创建订单
        //5.1使用全局id生成器生成订单id
        Long orderId = Long.valueOf(idGenUtil.generateId("order"));
        //5.2.保存订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        save(voucherOrder);
        return orderId;
    }
}
